<template>
  <d2-container type="full">
    <mk-search-form :model="query" @search="getData()">
      <el-form-item class="inline-item" prop="dayDate">
        <el-date-picker v-model.trim="query.selMonth" type="month" size="mini" value-format="yyyy-MM" clearable
          placeholder="选择月份">
        </el-date-picker>
      </el-form-item>
    </mk-search-form>
    <div class="table-operate">
      <el-button size="mini" icon="el-icon-upload" @click="exportEcx">导出</el-button>
    </div>
    <el-table :data="dayArr" :height="heightL" :row-style="rowStyle" style="margin-top: 20px" id="tabledatalist">
      <el-table-column prop="day" :label="query.selMonth.slice(-2) + '月'" min-width="100" align="center" fixed="left">
        <template slot-scope="scope">
          {{ scope.row.type ? scope.row.type : scope.row.day + '日' }}
        </template>
      </el-table-column>
      <template v-for="(item, index) in tableData">
        <el-table-column :label="shopList[index]" align="center">
          <el-table-column label="销售额" align="center">
            <el-table-column :prop="`${index}-sportPayables`" label="体彩机" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].sportPayables) ? item[scope.row.day -
                  1].sportPayables : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-luckyPayables`" label="福彩机" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].luckyPayables) ? item[scope.row.day -
                  1].luckyPayables : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-scratchCardPayables`" label="刮卡" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].scratchCardPayables) ? item[scope.row.day -
                  1].scratchCardPayables : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-dayIncomePaymentCode`" label="收款码" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dayIncomePaymentCode) ? item[scope.row.day -
                  1].dayIncomePaymentCode : '--' }}
              </template>
            </el-table-column>
            <el-table-column :prop="`${index}-totalPayables`" label="店总额" align="center" min-width="75">
              <template slot-scope="scope">
                {{ (item[scope.row.day - 1] && item[scope.row.day - 1].totalPayables) ? item[scope.row.day -
                  1].totalPayables : '--' }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <el-table-column min-width="40" class-name="occupy-black" align="center"></el-table-column>
      </template>
      <el-table-column prop="total" label="销售总额" align="center" min-width="75">
        <template slot-scope="scope">
          {{ totalList[scope.row.day - 1] || '--' }}
        </template>
      </el-table-column>
    </el-table>
  </d2-container>
</template>

<script>
import { getSalesStatistics, getSalesStatisticsTotal, getMonthProportion, getEachStoreProportion } from '@/api/modules/sys.report.api'
import Tools from '@/libs/utils.tool'
import { exportExecl } from '@/libs/util.export'
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  name: 'index',
  data() {
    return {
      query: {
        selMonth: Tools.fmtLong2DateTime(new Date(), 'yyyy-MM')
      },
      dayArr: [],
      tableData: [],
      totalList: [],
      shopList: [],
      mp: null,
      ep: null,
      heightL: null
    }
  },
  created() {
    this.getData()
    this.getWinHeight()
  },
  methods: {
    // 获取所有数据
    async getData() {
      // 清空表单值
      this.tableData = []
      this.dayArr = []
      this.totalList = []

      const date = new Date(this.query.selMonth)
      date.setDate(1)
      const firstDay = date.toLocaleDateString()
      const dateEnd = new Date(this.query.selMonth)
      dateEnd.setMonth(dateEnd.getMonth() + 1)
      dateEnd.setDate(0)
      const lastDay = dateEnd.toLocaleDateString()
      // 所有数据
      const res = await getSalesStatistics({
        startTime: `"${firstDay}"`,
        endTime: `"${lastDay}"`
      })
      const shopList = []
      const retArr = []
      // 将不同的店区分开
      res.map(item => {
        if (shopList.includes(item.shop)) {
          retArr[shopList.indexOf(item.shop)].push(item)
        } else {
          shopList.push(item.shop)
          retArr.push([item])
        }
      })

      // 合计数据
      const resTotal = await getSalesStatisticsTotal({
        startTime: `"${firstDay}"`,
        endTime: `"${lastDay}"`
      })

      // 店内各项销售占比
      this.mp = await getMonthProportion({
        startTime: `"${firstDay}"`,
        endTime: `"${lastDay}"`
      })

      // 店内各项销售占比
      this.ep = await getEachStoreProportion({
        startTime: `"${firstDay}"`,
        endTime: `"${lastDay}"`
      })

      this.shopList = shopList

      this.handleData(retArr, resTotal)
    },
    // 数据处理
    handleData(res, resTotal) {
      // 获取本月总共多少天
      const days = new Date(new Date(this.query.selMonth).getFullYear(), new Date(this.query.selMonth).getMonth() + 1, 0).getDate()
      // 创建本月所有的天
      let totalSum = 0
      for (let i = 1; i <= days; i++) {
        this.dayArr.push({ day: i })
        let temp = ''
        // 处理销售总额
        for (let j = 0; j < resTotal.length; j++) {
          if (Number(Tools.fmtLong2DateTime(resTotal[j].dayDate, 'dd')) === i) {
            temp = resTotal[j].totalValue
            break
          }
        }
        totalSum += Number(temp)
        this.totalList.push(temp)
      }
      this.totalList.push(totalSum)
      // 插入合计数据
      this.dayArr.push({ day: this.dayArr.length + 1, type: '合计' })
      this.dayArr.push({ day: this.dayArr.length + 1, type: '店内各项销售占比' })
      this.dayArr.push({ day: this.dayArr.length + 1, type: '各店销售占比' })
      // 处理数据将每一个店的时间对应上列
      const tableData = []

      res.map((dayData, index) => {
        const oneDay = []
        for (let i = 1; i <= days; i++) {
          let temp = { day: i }
          for (let j = 0; j < dayData.length; j++) {
            if (Number(Tools.fmtLong2DateTime(dayData[j].dayDate, 'dd')) === i) {
              temp = { ...temp, ...dayData[j] }
              break
            }
          }
          oneDay.push(temp)
        }
        // 求合
        oneDay.push({
          sportPayables: this.mp[index].sportPayablesTotal,
          luckyPayables: this.mp[index].luckyPayablesTotal,
          scratchCardPayables: this.mp[index].scratchCardPayablesTotal,
          dayIncomePaymentCode: this.mp[index].dayIncomePaymentCodeTotal,
          totalPayables: this.mp[index].totalPayablesTotal
        })
        // 处理接口数据
        oneDay.push({
          sportPayables: this.mp[index].sportPayablesProportion.toFixed(2) + '%',
          luckyPayables: this.mp[index].luckyPayablesProportion.toFixed(2) + '%',
          scratchCardPayables: this.mp[index].scratchCardPayablesProportion.toFixed(2) + '%',
          // dayIncomePaymentCode: (this.mp[index].dayIncomePaymentCodeProportion || 0).toFixed(2) + '%',
        })

        oneDay.push({
          totalPayables: this.ep[index].field_percentage.toFixed(2) + '%'
        })

        tableData.push(oneDay)
      })

      this.tableData = tableData
    },
    // 改变样式
    rowStyle(obj) {
      if (obj.row.type) {
        return { backgroundColor: '#F5F7FA !important' }
      }
    },
    //获取窗口高度
    getWinHeight() {
      let that = this
      this.heightL = window.innerHeight - 220
      window.addEventListener('resize', () => {
        that.heightL = window.innerHeight - 270
      })
    },

    // 导出
    exportEcx() {
      // console.log('dayArrtable', JSON.stringify(this.$refs.dayArrtable))
      // console.log('dayArrtacolumnsble', this.$refs.dayArrtable.columns)
      // var headerlist = []
      // for (let index = 0; index < this.$refs.dayArrtable.columns.length; index++) {
      //   const element = this.$refs.dayArrtable.columns[index];
      //   headerlist.push({ name: element.label, key: element.property })
      // }

      // exportExecl(this, headerlist, this.tableData, '列表', new Date().toLocaleDateString() + '导出的列表')
      this.exportExceldata(new Date().toLocaleDateString() + '导出的列表', 'tabledatalist')
    },

    exportExceldata(filename, tableId) {
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var table = document.querySelector("#" + tableId).cloneNode(true);
      var wb = XLSX.utils.table_to_book(table, xlsxParam);
      /* 获取二进制字符进行输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          filename + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },
  }
}
</script>

<style>
.occupy-black {
  background-color: #F5F7FA !important;
  border-bottom: #F5F7FA !important;
}
</style>
